package service

import (
	"fmt"
	"log"
	"sync"

	"test-gin/entity"
	"test-gin/utils"

	"gorm.io/gorm"
)

type I18nService struct {
	db *gorm.DB
}

var i18nService *I18nService
var onceI18nService sync.Once

func GetI18nService() *I18nService {
	onceI18nService.Do(func() {
		log.Println("Starting to initialize I18nService...")
		db, err := utils.GetDB()
		if err != nil {
			log.Printf("Error getting DB connection: %v\n", err)
			panic(err)
		}
		log.Println("Got DB connection, starting auto migration...")
		// 自动迁移表结构
		err = db.AutoMigrate(&entity.I18nEntity{}, &entity.LanguageEntity{})
		if err != nil {
			log.Printf("Error during auto migration: %v\n", err)
			panic(err)
		}
		log.Println("Auto migration completed successfully")
		i18nService = &I18nService{db: db}
		log.Println("I18nService initialized successfully")
	})
	return i18nService
}

// SaveTranslation 保存国际化翻译
func (s *I18nService) SaveTranslation(app, server, key, language, value string) error {
	log.Printf("Saving translation: app=%s, server=%s, key=%s, language=%s, value=%s\n", app, server, key, language, value)
	// 保存当前翻译
	i18n := entity.I18nEntity{
		App:      app,
		Server:   server,
		Key:      key,
		Language: language,
		Value:    value,
	}
	if err := s.db.Save(&i18n).Error; err != nil {
		log.Printf("Failed to save translation: %v\n", err)
		return err
	}

	// 如果是中文翻译，则自动翻译为其他支持的语言
	if language == "zh" {
		log.Println("Detected Chinese translation, starting auto-translation...")
		// 获取所有支持的语言（除了中文）
		languages, err := s.GetSupportedLanguages()
		if err != nil {
			log.Printf("Failed to get supported languages: %v\n", err)
			return err
		}
		log.Printf("Found %d supported languages\n", len(languages))

		// 遍历所有支持的语言，调用飞书翻译接口进行翻译
		feishuService := GetFeishuService()
		for _, lang := range languages {
			log.Printf("Processing language: %s\n", lang.Code)
			if lang.Code == "zh" {
				log.Println("Skipping Chinese language\n")
				continue // 跳过中文
			}

			// 调用飞书翻译接口
			log.Printf("Calling Feishu translate API for %s\n", lang.Code)
			translatedValue, err := feishuService.Translate("zh", lang.Code, value)
			if err != nil {
				// 翻译失败不影响主流程，只记录错误
				log.Printf("Failed to translate to %s: %v\n", lang.Code, err)
				continue
			}
			log.Printf("Translated to %s: %s\n", lang.Code, translatedValue)

			// 只有当翻译结果不为空时，才保存翻译记录
			if translatedValue != "" {
				// 保存翻译结果
				translatedI18n := entity.I18nEntity{
					App:      app,
					Server:   server,
					Key:      key,
					Language: lang.Code,
					Value:    translatedValue,
				}
				if err := s.db.Save(&translatedI18n).Error; err != nil {
					log.Printf("Failed to save translation for %s: %v\n", lang.Code, err)
				} else {
					log.Printf("Saved translation for %s successfully\n", lang.Code)
				}
			} else {
				log.Printf("Skipping empty translation for %s\n", lang.Code)
			}
		}
	}

	return nil
}

// AddLanguage 添加支持的语言
func (s *I18nService) AddLanguage(code, name string) error {
	language := entity.LanguageEntity{
		Code:     code,
		Name:     name,
		IsActive: true,
	}
	return s.db.Save(&language).Error
}

// GetSupportedLanguages 获取所有支持的语言
func (s *I18nService) GetSupportedLanguages() ([]entity.LanguageEntity, error) {
	var languages []entity.LanguageEntity
	err := s.db.Where("is_active = ?", true).Find(&languages).Error
	return languages, err
}

// GetTranslationsByAppAndLanguage 按app和语言获取翻译
func (s *I18nService) GetTranslationsByAppAndLanguage(app, language string) (map[string]string, error) {
	var translations []entity.I18nEntity
	err := s.db.Where("app = ? AND language = ?", app, language).Find(&translations).Error
	if err != nil {
		return nil, err
	}

	result := make(map[string]string)
	for _, t := range translations {
		// 构建三级key: app.server.key
		fullKey := fmt.Sprintf("%s.%s.%s", t.App, t.Server, t.Key)
		result[fullKey] = t.Value
	}

	return result, nil
}

// GetTranslationsByAppAndLanguageGrouped 按app和语言获取翻译，并按server分组
func (s *I18nService) GetTranslationsByAppAndLanguageGrouped(app, language string) (map[string]map[string]string, error) {
	var translations []entity.I18nEntity
	err := s.db.Where("app = ? AND language = ?", app, language).Find(&translations).Error
	if err != nil {
		return nil, err
	}

	result := make(map[string]map[string]string)
	for _, t := range translations {
		if _, ok := result[t.Server]; !ok {
			result[t.Server] = make(map[string]string)
		}
		result[t.Server][t.Key] = t.Value
	}

	return result, nil
}

// UpdateLanguageStatus 更新语言状态
func (s *I18nService) UpdateLanguageStatus(code string, isActive bool) error {
	return s.db.Model(&entity.LanguageEntity{}).Where("code = ?", code).Update("is_active", isActive).Error
}

// GetAllTranslations 获取所有翻译
func (s *I18nService) GetAllTranslations() ([]entity.I18nEntity, error) {
	var translations []entity.I18nEntity
	err := s.db.Find(&translations).Error
	return translations, err
}

// SearchTranslations 搜索翻译
func (s *I18nService) SearchTranslations(app, server, language string) ([]entity.I18nEntity, error) {
	var translations []entity.I18nEntity
	query := s.db.Model(&entity.I18nEntity{})
	
	if app != "" {
		query = query.Where("app = ?", app)
	}
	if server != "" {
		query = query.Where("server = ?", server)
	}
	if language != "" {
		query = query.Where("language = ?", language)
	}
	
	err := query.Find(&translations).Error
	return translations, err
}

// DeleteTranslation 删除单个翻译
func (s *I18nService) DeleteTranslation(app, server, key, language string) error {
	return s.db.Where("app = ? AND server = ? AND `key` = ? AND language = ?", app, server, key, language).Delete(&entity.I18nEntity{}).Error
}

// BatchDeleteTranslations 批量删除翻译
func (s *I18nService) BatchDeleteTranslations(translations []entity.I18nEntity) error {
	for _, t := range translations {
		if err := s.db.Where("app = ? AND server = ? AND `key` = ? AND language = ?", t.App, t.Server, t.Key, t.Language).Delete(&entity.I18nEntity{}).Error; err != nil {
			return err
		}
	}
	return nil
}
